package org.qydjk.console.service.impl;

import org.qydjk.common.pojo.user.User;
import org.qydjk.common.pojo.user.UserCapitalWater;
import org.qydjk.common.pojo.user.UserMoneyDetail;
import org.qydjk.common.service.impl.BaseService;
import org.qydjk.common.vo.ext.UserCapitalWaterEnum;
import org.qydjk.console.service.IUserService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by ASUS on 2017/12/15.
 */
@Service
public class UserService extends BaseService implements IUserService {
    /**
     * 加减余额  0,加  1,减
     */
    public void addOrSubtractMoney(User user, UserCapitalWaterEnum en, String money) throws Exception {
        BigDecimal decMoney = new BigDecimal(money);
        Date date = new Date();
        BigDecimal userMoney = user.getMoney();
        if (userMoney == null ){
            userMoney = new BigDecimal(0);
        }
        if (en.getType() == 0) {
            //加
            user.setMoney(userMoney.add(decMoney));
        } else if (en.getType() == 1) {
            //减
            user.setMoney(userMoney.subtract(new BigDecimal(money)));
            decMoney = new BigDecimal(0).subtract(decMoney);//操作金额 扣款为负("-")
        }
        baseDao.update(user);

        //余额明细
        String findDetailBefSql = "SELECT * " +
                " FROM qy_user_money_detail u " +
                " WHERE u.user_id = " + user.getId() + " " +
                " ORDER BY u.id DESC";
        UserMoneyDetail userMoneyDetailPre = baseDao.findSingleBySQL(findDetailBefSql, UserMoneyDetail.class);
        if (userMoneyDetailPre == null) {
            userMoneyDetailPre = new UserMoneyDetail();
            userMoneyDetailPre.setAftMoney(new BigDecimal(0));
        }
        UserMoneyDetail userMoneyDetail = new UserMoneyDetail();
        userMoneyDetail.setUserId(user.getId());
        userMoneyDetail.setPreMoney(userMoneyDetailPre.getAftMoney());//操作前金额
        userMoneyDetail.setOpMoney(decMoney); //操作金额 扣款为负("-")
        userMoneyDetail.setAftMoney(userMoneyDetail.getPreMoney().add(decMoney));//操作后金额
        userMoneyDetail.setOpTime(date);
        userMoneyDetail.setOpType(en.getType());
        userMoneyDetail.setCreateTime(date);
        userMoneyDetail.setUpdateTime(date);
        baseDao.save(userMoneyDetail);

        //操作资金流水
        UserCapitalWater userCapitalWater = new UserCapitalWater();
        userCapitalWater.setUserId(user.getId());
        userCapitalWater.setType(en.getType());
        userCapitalWater.setTypeName(en.getTypeName());
        userCapitalWater.setCreateTime(date);
        userCapitalWater.setUpdateTime(date);
        userCapitalWater.setVal(decMoney);//流水金额  扣款为负("-")
        baseDao.save(userCapitalWater);
    }
}
